package com.music.common.presentation.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.music.common.entity.UserDetail;
import com.music.common.entity.UserSettings;
import com.music.common.errorhandler.PresentationException;
import com.music.common.presentation.forms.LandingForm;
import com.music.common.service.ILoginService;
import com.music.common.service.impl.LoginService;

public class LandingAction extends Action {

	private ILoginService loginService;

	/**
	 * @param documentServiceFacade
	 * 
	 *            public LandingAction(ILoginService loginService) {
	 *            this.loginService = loginService; }
	 */

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {

			loginService = new LoginService();
			// process the input
			LandingForm loginForm = (LandingForm) form;
			String userName = loginForm.getUsername();
			String password = loginForm.getPassword();
			request.setAttribute("result", userName);
			HttpSession session = request.getSession(false);
			UserSettings userSettings  = (UserSettings) session.getAttribute("userSettings");
			if(userSettings == null){
				boolean valid = loginService.authenticate(userName, password, request);
				if (valid) {
					userSettings = new UserSettings();
					UserDetail user = loginService.getUserDetails(userName, request);
					userSettings.setUserSessionActive(true);
					userSettings.setUserId(user.getUserId());
					userSettings.setUserType(user.getUserType());
					userSettings.setFirstName(user.getFirstName());
					userSettings.setLanguageCode("EN");
					userSettings.setLastName(user.getLastName());
					userSettings.setEmail(user.getEmail());
					session.setAttribute("userSettings", userSettings);
					
					return (mapping.findForward("success"));
				} else {
					session.setAttribute("login", false);
					return (mapping.findForward("fail"));
				}
			} else {
				return (mapping.findForward("success"));
			}
		} catch (Exception ex) {
			throw new PresentationException(ex);
		}
	}
}
